<?php
/**
 * datetime 2025/9/3 15:17
 */

namespace app\common\library;
class Crypto
{
    // 加密密钥（与前端保持一致）
    private static $key = 'ae0bbd2810ede227bbeec1b9442f83f4';
    private static $iv = 'e11a3cb5147fc2b1';
    private static $cipher_algo = 'AES-256-CBC';
    private static $options = OPENSSL_RAW_DATA;
    
    /**
     * AES解密
     * @param string $encryptedData 加密的字符串
     * @return mixed
     */
    public static function decrypt($encryptedData)
    {
        $decrypted = openssl_decrypt(
            base64_decode($encryptedData),
            self::$cipher_algo,
            self::$key,
            self::$options,
            self::$iv
        );
        // 尝试解析JSON
        $result = json_decode($decrypted, true);
        
        if (json_last_error() === JSON_ERROR_NONE) {
            return $result;
        }
        
        return $decrypted;
    }
    
    /**
     * AES加密
     * @param mixed $data 要加密的数据
     * @return string
     */
    public static function encrypt($data)
    {
        if (is_array($data) || is_object($data)) {
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        }
        $encrypted = openssl_encrypt(
            $data,
            self::$cipher_algo,
            self::$key,
            self::$options,
            self::$iv
        );
        return base64_encode($encrypted);
    }
}